package com.imy.rootserver.handler;

import android.app.UiAutomation;
import android.os.SystemClock;
import android.view.MotionEvent;

import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.uiautomator.Configurator;
import androidx.test.uiautomator.UiDevice;

import com.imy.rootserver.bean.GesturePoint;
import com.imy.rootserver.gesture.GestureHandler;
import com.imy.rootserver.gesture.InteractionController;
import com.imy.rootserver.screen.ScreenHandler;
import com.imy.rootserver.socket.TcpServer;

import static com.imy.rootserver.utils.ReflectionUtils.invoke;
import static com.imy.rootserver.utils.ReflectionUtils.method;

public class HandlerDispatch {
  private GestureHandler mGestureHandler;
  private UiDevice uiDevice;
  private InteractionController interactionController;
  private ScreenHandler mScreenHandler;

  public HandlerDispatch(TcpServer server) {
    int flags = UiAutomation.FLAG_DONT_SUPPRESS_ACCESSIBILITY_SERVICES;
    Configurator.getInstance().setUiAutomationFlags(flags);
    uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    Object getInteractionController = invoke(method(UiDevice.class, "getInteractionController"),
        uiDevice);
    //        Log.i(TAG, "getInteractionController" + getInteractionController);
    interactionController = new InteractionController(getInteractionController);
    mGestureHandler = new GestureHandler(interactionController);
    mScreenHandler = new ScreenHandler(uiDevice, server);
  }

  public void dispatchGesture(String event, float x, float y, int id) {
    synchronized (this) {
      switch (event) {
        case "d": {
          GesturePoint build =
              GesturePoint.Builder.builder(x, y, MotionEvent.ACTION_DOWN, id, SystemClock.uptimeMillis())
                  .build();
          mGestureHandler.down(build);
          break;
        }
        case "u": {
          GesturePoint build =
              GesturePoint.Builder.builder(x, y, MotionEvent.ACTION_UP, id, SystemClock.uptimeMillis())
                  .build();
          mGestureHandler.up(build);
          break;
        }
        case "m": {
          GesturePoint build =
              GesturePoint.Builder.builder(x, y, MotionEvent.ACTION_MOVE, id, SystemClock.uptimeMillis())
                  .build();
          mGestureHandler.move(build);
          break;
        }
        case "r":
          //释放所有键
          mGestureHandler.releaseAll();
          break;
      }
    }

  }



  public synchronized void dispatchScreen(String flag) {
    mScreenHandler.screen(flag);
  }
}
